package com.zhonghan.recharge.service.impl;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.qianmi.open.api.ApiException;
import com.qianmi.open.api.DefaultOpenClient;
import com.qianmi.open.api.OpenClient;
import com.qianmi.open.api.QianmiResponse;
import com.qianmi.open.api.domain.elife.OrderDetailInfo;
import com.qianmi.open.api.request.BmGasCardGetAccountInfoRequest;
import com.qianmi.open.api.request.BmGasCardPayBillRequest;
import com.qianmi.open.api.request.BmRechargeMobileGetPhoneInfoRequest;
import com.qianmi.open.api.request.GasCardGetAccountInfoRequest;
import com.qianmi.open.api.request.RechargeBaseGetItemInfoRequest;
import com.qianmi.open.api.request.RechargeMobileGetItemInfoRequest;
import com.qianmi.open.api.response.BmGasCardGetAccountInfoResponse;
import com.qianmi.open.api.response.BmGasCardPayBillResponse;
import com.qianmi.open.api.response.BmRechargeMobileGetPhoneInfoResponse;
import com.qianmi.open.api.response.GasCardGetAccountInfoResponse;
import com.qianmi.open.api.response.RechargeMobileGetItemInfoResponse;
import com.qianmi.open.api.tool.util.SignUtil;
import com.zhonghan.common.bean.Result;
import com.zhonghan.common.enums.ResultStatus;
import com.zhonghan.common.utils.BanMaSignUtil;
import com.zhonghan.common.utils.BanMaUtils;
import com.zhonghan.common.utils.JiSuOrder;
import com.zhonghan.common.utils.RechargeOrderId;
import com.zhonghan.recharge.controller.RechargeController;
import com.zhonghan.recharge.dao.BmItemDao;
import com.zhonghan.recharge.dao.ZhFillCardDao;
import com.zhonghan.recharge.dao.ZhGascardOrderDao;
import com.zhonghan.recharge.pojo.BmItem;
import com.zhonghan.recharge.pojo.ZhBusinessGascardOrder;
import com.zhonghan.recharge.pojo.ZhFillCard;
import com.zhonghan.recharge.pojo.ZhGascardOrder;
import com.zhonghan.recharge.service.IRechargeServcie;
import com.zhonghan.recharge.service.impl.jisu.BusinessJiSuRecharge;
import com.zhonghan.recharge.service.impl.jisu.JiSuRecharge;
import com.zhonghan.recharge.task.TaskList;

/**
 * 充油业务
 * @author Administrator
 *
 */
@Service
public class RechargeServiceImpl implements IRechargeServcie{

	
	private String api_url_1 = "http://test.api.bm001.com/api";
	private String province = "全国";
	private String cardInfoMethod="bm.elife.gasCard.getAccountInfo";
	//支付加油卡订单
	private String oilRechargeMethod="bm.elife.gasCard.payBill";
	
	//订单回调 请求
	private String order_callback = "http://www.zhkjnet.com/recharge/oil/callback";//"http://zhyyou.free.ngrok.cc/recharge/oil/callback";//
	
	private static final String api_url="http://api.bm001.com/api";
	private static final String APP_KEY ="10001782";
	private static final String APP_SECRET = "IKtXMSpY2rIxG2dG4KQb1mDEPPg2lLTP";
	public static final String APP_TOKEN = "0b5f57ffcbdc47eba3f89713119c3bf4";
	//中翰云加油站１号
	//private static final String APP_KEY ="10001749";
	//private static final String APP_SECRET ="XgfMQMQeNJxDka0bD5BCR490BDmmR5gP";
	//public static final String APP_TOKEN = "914dc12563a54138b0b060b380f5c3c3";
	
	protected static final OpenClient client = new DefaultOpenClient(api_url,APP_KEY, APP_SECRET);
	
	
	private static final Logger logger = LogManager.getLogger(RechargeServiceImpl.class);
	
	/*@Value("${qianmi.API_URL}")
	private String API_URL;
	*/
	
	//protected final 
	
	// 创建一个客户端，默认连接超时时间为3秒，请求超时时间为15秒。
    //protected OpenClient client = new DefaultOpenClient(API_URL, APP_KEY, APP_SECRET);
    
    public String getPhoneInfo(String operator,String gasCardNo) {
		
		/*
		 * 1.获取数字签名
		 * 1.1 拼接url  ：  bm_api+param
		 * 2.创建一个客户端对象
		 * 3.请求bm的api
		 * 4.处理响应信息
		 */
		
        try {
        	Map<String, String> param = new HashMap<>();
    		param.put("access_token", APP_TOKEN);
            param.put("v", "1.1");
            param.put("method", "bm.elife.recharge.mobile.getPhoneInfo");
            String nowDate = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date());
            //param.put("timestamp", nowDate);
            param.put("format", "json");
            param.put("phoneNo", "18672715876");
            //param.put("respType", "all");
			String sign = BanMaSignUtil.sign(param, APP_SECRET);
			//时间替换
			//param.put("timestamp", nowDate.replaceAll(" ", "+").replaceAll(":", "%3A"));
			String param1 = urlStr(param);
			
			//拼接url
			String url = api_url_1+"?sign="+sign+"&"+param1;
			//获取客户端对象
			logger.info(url);
			OpenClient client = new DefaultOpenClient(url, APP_KEY, APP_SECRET);
			BmRechargeMobileGetPhoneInfoRequest req = new BmRechargeMobileGetPhoneInfoRequest();
			req.setPhoneNo("18672715876");
			req.setRespType("all");
			BmRechargeMobileGetPhoneInfoResponse response = client.execute(req, APP_TOKEN);
			
			/*OpenClient client = new DefaultOpenClient(url,APP_KEY, APP_SECRET);
			BmGasCardGetAccountInfoRequest req = new BmGasCardGetAccountInfoRequest();
			req.setProvince(province);
			req.setOperator(operator);
			req.setGasCardNo(gasCardNo);
			BmGasCardGetAccountInfoResponse response = client.execute(req, BanMaUtils.TOKEN);*/
			
			if (!response.isSuccess()) {
	            handleError(response);
	            return "getAccountInfo-fail";
	        }
			String body = response.getBody();
			logger.info("查询到的信息"+body);
			return body;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
	}
    
    /**
     * 查询到返回true
     * 查询失败返回false
     */
	public boolean getRechargeCardInfo(String operator,String gasCardNo) {
		
		/*
		 * 1.获取数字签名
		 * 1.1 拼接url  ：  bm_api+param
		 * 2.创建一个客户端对象
		 * 3.请求bm的api
		 * 4.处理响应信息
		 */
        try {
        	if(client != null) {
        		logger.info("client ok..............");
        	}else {
        		logger.info("client filad...............");
        	}
        	//使用内置sdk
        	//OpenClient client = new DefaultOpenClient(api_url, APP_KEY, APP_SECRET);
			//获取客户端对象
			//openClient
        	 GasCardGetAccountInfoRequest req = new GasCardGetAccountInfoRequest();
             req.setProvince("全国");
     		req.setOperator(operator);
     		req.setGasCardNo(gasCardNo);
     		req.setTimestamp((new Date()).getTime());
     		GasCardGetAccountInfoResponse response = client.execute(req, APP_TOKEN);
     		logger.info("查询卡状态："+response.getErrorCode()+" "+response.getMsg());
     		if (!response.isSuccess()) {
                 handleError(response);
                 return false;
             }
			String body = response.getBody();
			logger.info("查询到的信息"+body);
			return true;
		} catch (ApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		
		return false;
	}
	public String urlStr(Map<String, String> param) {
		StringBuilder strBuilder = new StringBuilder();
		Iterator<String> iterator = param.keySet().iterator();
		while(iterator.hasNext()) {
			String key = iterator.next();
			strBuilder.append(key+"="+param.get(key)).append("&");
		}
		return strBuilder.deleteCharAt(strBuilder.length()-1).toString();
	}
	private void handleError(QianmiResponse response) {
        logger.info(response.getSubCode() + ":" + response.getSubMsg());
        // handle the error
    }
	
	public void oilRecharge2(String gasnumber,String gasname, String gasphone,String recardno) {
		
		
		String itemId="64357113";
		String myorderId = "201801161011";
		oilRechargeBill(itemId,myorderId,gasnumber,gasname,gasphone,recardno,null);
	}
	
	
	/**
	 * 极速数据充值
	 *  myorderId 系统充值orderid
	 * gasnumber 持卡 卡号
	 * gasname   持卡人姓名
	 * gasphone  持卡人电话
	 * recardno 充值卡 卡号
	 * amount  充值金额
	 */
	
	/**
	 * 充油 
	 * itemId  斑马商品id
	 * myorderId 系统充值orderid
	 * gasnumber 持卡 卡号
	 * gasname   持卡人姓名
	 * gasphone  持卡人电话
	 * recardno 充值卡 卡号
	 * password 充值卡 密码
	 */
	public OrderDetailInfo oilRechargeBill(String itemId,String myorderId,String gasnumber,String gasname, String gasphone,String recardno, String password){
		try {
			
			if(client != null) {
        		logger.info("client ok..............");
        	}else {
        		logger.info("client filad...............");
        	}
			
			BmGasCardPayBillRequest req = new BmGasCardPayBillRequest();
			req.setItemId(itemId);
			req.setOuterTid(myorderId);
			//
			req.setGasCardTel(gasphone);
			req.setGasCardName(gasname);
			req.setGasCardNo(gasnumber);
			//req.setCallback(order_callback);
			BmGasCardPayBillResponse response = client.execute(req, APP_TOKEN);
			logger.info("充值过程："+response.getErrorCode()+" "+response.getMsg());
			if (!response.isSuccess()) {
                handleError(response);
                return null;
            }
			
			//获取充值信息
			OrderDetailInfo orderDetailInfo = response.getOrderDetailInfo();
			return orderDetailInfo;
		} catch (ApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
		
	}
	/**
	 * 充油 
	 * @param itemId
	 * @param myorderId
	 * @param gasnumber
	 * @param gasname
	 * @param gasphone
	 * @param recardno
	 * @param password
	 * @return
	 */
	public Result oilRechargeBillII(String itemId,String myorderId,String gasnumber,String gasname, String gasphone,String recardno, String password){
		try {
			
			if(client != null) {
        		logger.info("client ok..............");
        	}else {
        		logger.info("client filad...............");
        	}
			Result result_bm = new Result();
			BmGasCardPayBillRequest req = new BmGasCardPayBillRequest();
			req.setItemId(itemId);
			logger.info("myorderId="+myorderId);
			if(myorderId.length()<=8) {
				return null;
			}
			req.setOuterTid(myorderId);
			//
			req.setGasCardTel(gasphone);
			req.setGasCardName(gasname);
			req.setGasCardNo(gasnumber);
			req.setCallback(order_callback);
			BmGasCardPayBillResponse response = client.execute(req, APP_TOKEN);
			logger.info("充值过程："+response.getErrorCode()+" "+response.getMsg());
			if (!response.isSuccess()) {
				
				logger.info(response.getSubCode() + response.getSubMsg());
				result_bm.setCode(response.getSubCode());
				result_bm.setMsg("系统维护，请稍后再试");
                return result_bm;
            }else {
            	//获取充值信息
    			OrderDetailInfo orderDetailInfo = response.getOrderDetailInfo();
    			result_bm.setCode("1");
				result_bm.setMsg("充油成功");
				result_bm.setData(orderDetailInfo.getBillId());
    			return result_bm;
            }
		} catch (ApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
		
	}
	/**
	 * 油卡充值服务
	 * @param gasnumber  油卡卡号
	 * @param gasname   持卡人
	 * @param gasphone  持卡人电话
	 * @param gastype   油卡类型
	 * @param recardno  序列号
	 * @param password  序列号密码
	 * @param openid
	 * @return
	 */
	@Autowired
    private ZhFillCardDao zhFillCardDao;
	@Autowired
    private BmItemDao bmItemDao;
	@Autowired
    private ZhGascardOrderDao zhGascardOrderDao;
	
	@Transactional
	public Result insertOilRechargeService(String gasnumber, String gasname, String gasphone, String gastype, String recardno,
			String password,String openid){
		Result result = new Result();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		// 判断
		ZhFillCard zfc = new ZhFillCard();
		zfc.setSequence(recardno);
		zfc.setPassword(password);
		//List<ZhFillCard> zfcList = zhFileCardService.selectZhFillCardByObj(zfc );
		List<ZhFillCard> zfcList = zhFillCardDao.selectZhFillCardByObj(zfc);
		logger.info("查询到充值卡："+zfcList.size());
		if(zfcList!=null && zfcList.size()>0){
			// 查询到充值卡信息,保存订单
			zfc = zfcList.get(0);
			if(zfc.getStatus()==2){
				// 卡已消费
				result.setCode("0");
				result.setMsg("对不起,您输入的卡号已经被消费");
				logger.info("充值卡已消费.....");
				return result;
			}else if(zfc.getStatus()==-1){
				// 卡已消费
				result.setCode("0");
				result.setMsg("对不起,您输入的卡号未激活");
				logger.info("充值卡未激活.....");
				return result;
			}
			ZhGascardOrder zgo = new ZhGascardOrder();
			//zgo.setOrderNo(UUID.randomUUID().toString().replace("-", ""));
			String orderId = RechargeOrderId.getOrderIdII(recardno);
			zgo.setOrderNo(orderId);
			// 通过油卡信息中的充值面额去斑马商品中查询对应的商品编号
			BmItem bt = new BmItem();
			bt.setFacePrice(zfc.getFacePrice());
			bt.setOperatorType(gastype); // 加油卡的类型
			//List<BmItem> biList = bmItemService.selectBmItemByObj(bt);
			List<BmItem> biList = bmItemDao.selectBmItemByObj(bt);
			logger.info("查询到斑马商品："+biList.size());
			if(biList!=null && biList.size()>0){
				bt = biList.get(0); // 获取斑马商品信息
				zgo.setBmItemId(bt.getBmItemId());
				zgo.setRechargeAmount(zfc.getFacePrice());
				zgo.setBmItemName(bt.getItemName());
				zgo.setBmItemNum(1);
				zgo.setOpenid(openid);
				zgo.setGascardNo(gasnumber);
				zgo.setTelephone(gasphone);
				zgo.setRechargeState("0");  // 充值状态 0 充值中，1 成功
				zgo.setSalePrice(zfc.getFacePrice());   
				zgo.setOrderType("banma");
				zgo.setFillCardSequence(zfc.getSequence());
				zgo.setBmItemId(bt.getBmItemId());
				zgo.setFacePrice(zfc.getFacePrice());
				zgo.setOrderTime(sdf.format(new Date()));
				
				zgo.setFillName(gasname);
				zgo.setOperateTime("");
				int rs = zhGascardOrderDao.insertNonEmptyZhGascardOrder(zgo);
				logger.info("生成本地订单："+rs);
				if(rs >0){
					// 订单创建成功并更改中翰云油充值卡状态为已消费
					zfc.setStatus(2);
					zfc.setConsumeTime(sdf.format(new Date()));
					zfc.setReceiveTelephone(gasphone);
					int zfcs = zhFillCardDao.updateNonEmptyZhFillCardById(zfc);
					logger.info("订单创建成功，更改充值的状态为已消费："+zfcs);
					// 添加订单成功,则调用千米平台扣款充值
					/**
					 * bm商品id
					 * 本地订单id
					 */
					
					logger.info("准备调用斑马接口");
					//OrderDetailInfo  bmOrderInfo = oilRechargeBill(bt.getBmItemId(),zgo.getOrderNo(),gasnumber, gasname, gasphone, recardno,null);
					Result oil_result = oilRechargeBillII(bt.getBmItemId(),zgo.getOrderNo(),gasnumber, gasname, gasphone, recardno,null);
					if(oil_result != null && "1".equals(oil_result.getCode())) {
						//OrderDetailInfo bmOrderInfo = (OrderDetailInfo)oil_result.getData();
						
						result.setCode("1");
						result.setMsg("油卡充值成功!");
						//result.setData(DOMAIN + "/recharge/oil/card/result?orderNo=" + zgo.getOrderNo());
						//更改订单状态
						zhGascardOrderDao.updateRechargeStateByOrderNo(orderId, "0",oil_result.getData().toString());
						logger.info("订单"+orderId+"生成成功");
						result.setData(zgo.getOrderNo());
						
						
						return result;
					}else {
						logger.info("获取斑马订单失败..................");
						logger.info("油卡充值失败..............");
						/**
						 * 更改卡片状态
						 */
						int num = zhGascardOrderDao.updateRechargeStateByOrderNo(orderId, "9","faild");
						if(num>=1) {
							zhFillCardDao.updateStatusBySequence("1", zfc.getSequence());
						}
						
						
						result.setCode("0");
						result.setMsg("油卡充值失败,请稍后再试");
						
						//throw new RuntimeException(JSON.toJSONString(oil_result));
					}
				}else {
					//订单没有创建成功
					// 没有找到斑马商品
					result.setCode("0");
					result.setMsg("订单创建失败");
					//throw new Exception(JSON.toJSONString(result));
					
				}
				
			}else {
				// 没有找到斑马商品
				result.setCode("0");
				result.setMsg("没有找到斑马商品");
			}
			
			
		}else{
			// 没有查询到油卡信息
			result.setCode("0");
			result.setMsg("充值卡序列号或密码不正确,请检查好后重新输入");
		}
				
		return result;
	}
	/**
	 * 
	 * @param gasnumber  油卡卡号
	 * @param gasname
	 * @param gasphone
	 * @param gastype
	 * @param money     面额
	 * @return
	 * @throws Exception
	 */
	public Result insertOilRechargeServiceFromGasnumber(String gasnumber, String gasname, String gasphone, String gastype,Integer money){
		Result result = new Result();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		
		// 通过油卡信息中的充值面额去斑马商品中查询对应的商品编号
		BmItem bt = new BmItem();
		bt.setFacePrice(money);
		bt.setOperatorType(gastype); // 加油卡的类型
		//List<BmItem> biList = bmItemService.selectBmItemByObj(bt);
		List<BmItem> biList = bmItemDao.selectBmItemByObj(bt);
		BmItem bmItem = biList.get(0);
		if(bmItem != null) {
			ZhGascardOrder zgo = new ZhGascardOrder();
			
			String orderId = RechargeOrderId.getOrderIdBigCustomer();
			zgo.setOrderNo(orderId);
			zgo.setBmItemId(bmItem.getBmItemId());
			zgo.setRechargeAmount(bmItem.getFacePrice());
			zgo.setBmItemName(bmItem.getItemName());
			zgo.setBmItemNum(1);
			zgo.setOpenid("bigCustomer");
			zgo.setGascardNo(gasnumber);
			zgo.setTelephone(gasphone);
			zgo.setRechargeState("0");  // 充值状态 0 充值中，1 成功
			zgo.setSalePrice(bmItem.getFacePrice());   
			zgo.setOrderType("banma");   //调用斑马订单
			zgo.setBmItemId(bt.getBmItemId());
			zgo.setFacePrice(bmItem.getFacePrice());
			zgo.setOrderTime(sdf.format(new Date()));
			//记录大客户
			zgo.setFillCardSequence("bigCustomer");
			zgo.setFillName(gasname);
			zgo.setOperateTime("");
			int rs = zhGascardOrderDao.insertNonEmptyZhGascardOrder(zgo);
			logger.info("生成本地订单："+rs);
			/**
			 * bm商品id
			 * 本地订单id
			 */
			
			logger.info("准备调用斑马接口:"+bt.getBmItemId()+" "+zgo.getOrderNo()+" "+gasnumber+" "+gasname+" "+gasphone);
			Result oil_result = oilRechargeBillII(bt.getBmItemId(),zgo.getOrderNo(),gasnumber, gasname, gasphone, "",null);
			//Result oil_result = JiSuRecharge.toRecharge(orderId, gasnumber, gasname, gasphone, money);//oilRechargeBillII(bt.getBmItemId(),zgo.getOrderNo(),gasnumber, gasname, gasphone, recardno,null);
			
			/*Result oil_result = new Result();
			oil_result.setCode("1");
			oil_result.setData("test_api");*/
			if(oil_result != null && "1".equals(oil_result.getCode())) {
				//OrderDetailInfo bmOrderInfo = (OrderDetailInfo)oil_result.getData();
				
				result.setCode("1");
				result.setMsg("油卡充值成功!");
				//result.setData(DOMAIN + "/recharge/oil/card/result?orderNo=" + zgo.getOrderNo());
				//更改订单状态
				zhGascardOrderDao.updateRechargeStateByOrderNo(orderId, "0",oil_result.getData().toString());
				logger.info("订单"+orderId+"生成成功");
				result.setData(zgo.getOrderNo());
				
				
				return result;
			}else {
				logger.info("获取斑马订单失败..................");
				logger.info("油卡充值失败..............");
				
				zhGascardOrderDao.updateRechargeStateByOrderNo(orderId, "9","faild");
				result.setCode("0");
				result.setMsg("油卡充值失败,请稍后再试");
				
				//throw new RuntimeException(JSON.toJSONString(oil_result));
			}
		}else {
			result.setCode("0");
			result.setMsg("未找到该充值类型");
		}
				
		return result;
	}
	
}
